//table
function ctrlInitArrowTable(context, selector, data){
	if( $(context).is(selector) )
		var context = $(selector);
	else
		var context = $(selector, context);
	
	//if(context)
	//	CtrlAjax.addPartialUpdate(context,[".ctrl-table-paging", ".ctrl-table>tbody", ".ctrl-table-header-set-filters"]);
	
	
	var saveFilterCheckbox = $(context).find(".ctrl-table-filters-save");
	var offset = context.parents("div:eq(0)").offset();
		
	if(offset && false){
		$(".ctrl-browser-list-container").scrollTop( 0 );
		var offset = context.parents("div:eq(0)").offset();
		
		var td = context.find(".ctrl-table-header").children("th");
		context.children("tbody").css("padding-top", $("thead", context).height());
		$("thead", context).clone(true).insertBefore($("thead", context))
		.css({position: 'fixed', top: offset.top+ context.scrollTop(), "width": "100%" })
		.width(context.width())
		.find(".ctrl-table-header th").each(function(index, el ){
			if($.browser.mozilla)
				$(el).width( td.eq(index).width());
			else
				$(el).width( td.eq(index).width()+1);
		});
		
		//$("tfoot", context).css({position: 'fixed'});
	}
		
	//start filter
	
	$(".ctrl-table-filter", context).find(".ctrl-popup-cancel").click(function(){
		$(".ctrl-popup").remove();
	});
	
	$(".ctrl-table-filter", context).find(".ctrl-popup-submit").click(function(){
		var registry = CtrlAjax.getStateVar(context, 'filtersRegistry');
		
		if(registry != undefined)
			registry = registry.replace(new RegExp('%3D', 'g'), '=');
		
		var input = $(this).prevAll( "input:eq(0)" );
		var field = $(this).parents(".ctrl-table-filter").find("[name='field']").val();
		
		if(registry != undefined && registry != "W10=" && registry != "W10"){
			
			var count = registry.length % 4;
			if(count > 0)
				count = 4 - count;
			for(var i = 0; i < count; i++)
				registry += '=';
			
			var code = "registry = (" + decode64(registry) + ");";
			try{
				registry = eval(code);
			}catch(er){
				$.cookie(data['globalId'], null);
				
			}
		}else{
			registry = { };
		}
		
		var tmp = {};
		if($(this).parent().is(".ctrl-table-filter-range")){
			var inputs = $(this).parent().find("input[type=text]");
			if(inputs.eq(0).val().length > 0 || inputs.eq(1).val().length > 0)
				tmp.value = inputs.eq(0).val() + "_arrow_range_" + inputs.eq(1).val();
			else
				tmp.value = false;
		}else if($(this).parent().is(".ctrl-table-filter-boolean")){
			tmp.value = $(this).parent().find("input[type=radio]:checked").val();
		}else if($(this).parent().is(".ctrl-table-filter-date")){
			var inputs = $(this).parent().find("input[field]");
			if(inputs.eq(0).val().length > 0 || inputs.eq(1).val().length > 0)
				tmp.value = inputs.eq(0).val() + "_arrow_date_" + inputs.eq(1).val();
			else
				tmp.value = false;
		}else {
			if(input.val().length > 0)
				tmp.value = input.val();
			else
				tmp.value = false;
		}
		
		tmp.strict = false;
		if($(this).parents(".ctrl-table-filter").find("[name='strict']").size() > 0)
			tmp.strict = true;
		tmp.process = false;
		if($(this).parents(".ctrl-table-filter").find("[name='process']").size() > 0)
			tmp.process = true;
		
		//console.dir(registry);
		if(tmp.value !== false)
			registry[field] = tmp;
		else if (registry[field] != 'undefined')
			delete registry[field];
		
		registry  = encode64(JSON.stringify(registry));
		
		if(saveFilterCheckbox.attr('checked'))
			$.cookie(data['globalId'], registry, { expires: 30 });
		else
			$.cookie(data['globalId'], null);
		
		$(".ctrl-popup").remove();
		CtrlAjax.changeStateVars( context, {'filtersRegistry': registry, 'page': 0}, {}, function(){});
	});
	
	$(".ctrl-table-filter", context).find("select").change(function(){
		var registry = CtrlAjax.getStateVar(context, 'filtersRegistry');
		
		if(registry != undefined)
			registry = registry.replace(new RegExp('%3D', 'g'), '=');
		
		var input = $(this).prevAll( "input:eq(0)" );
		var field = $(this).parents(".ctrl-table-filter").find("[name='field']").val();
		
		if(registry != undefined && registry != "W10=" && registry != "W10"){
			
			var count = (registry.length % 4);
			if(count > 0)
				count = 4 - count;
			for(var i = 0; i < count; i++)
				registry += '=';
			
			var code = "registry = (" + decode64(registry) + ");";
			registry = eval(code);
		}else{
			registry = { };
		}
		
		var tmp = {};
		tmp.strict = false;
		if($(this).parents(".ctrl-table-filter").find("[name='strict']").size() > 0)
			tmp.strict = true;
		
		tmp.process = false;
		if($(this).parents(".ctrl-table-filter").find("[name='process']").size() > 0)
			tmp.process = true;
		
		option = $(this).parent().find("option:selected").eq(0);
		tmp.value = option.val() + "_arrow_sep_" +  option.text();
		
		registry[field] = tmp;
		registry  = encode64(JSON.stringify(registry));
		
		if(saveFilterCheckbox.attr('checked'))
			$.cookie(data['globalId'], registry, { expires: 30 });
		else
			$.cookie(data['globalId'], null);
		
		$(".ctrl-popup").remove();
		CtrlAjax.changeStateVars( context, {'filtersRegistry': registry, 'page': 0}, {}, function(){});
	});
	
	// remove filter action
	$(".ctrl-table-set-filter a", context).click(function() {
		
		if(saveFilterCheckbox.attr('checked'))
			$.cookie(data['globalId'], $(this).attr('rel'), { expires: 30 });
		else
			$.cookie(data['globalId'], null);
		
		return true;
	});
	
	$(".ctrl-table-remove-all-filters", context).click(function(){
		$.cookie(data['globalId'], null);
		CtrlAjax.changeStateVars( context, {'filtersRegistry': "W10=", 'page': 0}, {}, function(){});
	});
	
	$(".ctrl-table-filters-save", context).change(function() {
		
		if($(this).attr('checked'))
			$.cookie(data['globalId'], CtrlAjax.getStateVar(context, 'filtersRegistry'), { expires: 30 });
		else
			$.cookie(data['globalId'], null);
	});
	
	$(".ctrl-table-filter-show", context).click(function(){
		var trigger = $(this);
		var target = $(this).next().clone(true);
		
		popup = trigger.popup({
			el: target,
			open: true,
			dType: "leftTop",
			autoHide: false
		});
		
		$(target).find('.ctrl-table-filter-date input').datepicker({
			dateFormat: "dd.mm.yy"
		});
		
		$(target).find(":not([class~='ctrl-table-filter-date']) input:first").focus();
		
		return false; 
	});
	
	$(".ctrl-table-filter input[type=text]",context).keypress(function (e) {
		if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
			$(this).parent().find(".ctrl-popup-submit").click();
			return false;
		} else {
			return true;
		}
    });
	
	//end filter
	
	
	
	
	$(".ctrl-table-seach-area-trigger",context).click(
		function(event){
			var content = $(".ctrl-table-search-area-content",context);
			if(content.is(":visible")){
				if(CtrlAjax.getStateVar($(this), 'searchAreaExpanded') == 1)
					CtrlAjax.changeStateVars( $(this), {'searchAreaExpanded': 0}, {});
				else
					content.hide('slow');
			}else
				content.show('slow');
			return false;
		}
		
	);
	$(".ctrl-table-search-button", context).click(function(){
		var values = $(".ctrl-table-search-form", context).serialize();
		
		//console.dir(values);
		//alert(values);
		CtrlAjax.changeStateVars( this, {'searchAreaExpanded': 1, searchConditionsBase64: encode64(values)}, {}, function(el){
			var form = $(".ctrl-table-search-form", el);
			
			/*for(var i=0;i<values.length;i++){
				var input = form.find( "[name='" + values[i].name + "']");
				if( input.is(":checkbox") )
					input.attr('checked','checked');
				else if(  input.length > 1 ){
					input.each(function(){   
						if( $(this).val() == values[i].value )
							$(this).attr('checked','checked');
					});
				}else 
					input.val(values[i].value)
			}*/
			
		});
		
	});
	
	
	var sort = $(".ctrl-table-column-sort-desc,.ctrl-table-column-sort-asc",context);
	//alert("aaa");
	if(sort.length == 0 && $.tableDnD ){
		$(context).tableDnD({
	        onDrop: function(table, row) {
				var rows = table.tBodies[0].rows;
				var model = $(row).find(".ctrl-table-num").attr("model");
				
				var currRowId = row.id.replace("ctrl-row-", "");
				var rowsArr = new Array();
				for (var i=0; i<rows.length; i++) {
					var id = rows[i].id.replace("ctrl-row-", "");
					if( currRowId == id )
						var currRowIndex = i;
					rowsArr.push(id);
				}
				CtrlAjax.addShadow($(context));
				ArrowDataConnector.doAction(
						model, 
						currRowId,
						"move", 
						{
							prev: rowsArr[currRowIndex-1]?rowsArr[currRowIndex-1]:-1, 
							next: rowsArr[currRowIndex+1]?rowsArr[currRowIndex+1]:-1
						}, 
						{}, 
						function(response){
							CtrlAjax.changeStateVars($(row),{},{});
							
						}
				);
				
	        },
	        dragHandle: "ctrl-table-num"
	    });
		$(".ctrl-table-num").css("cursor", "n-resize");
	}
	
	$(".ctrl-table-num",context).mousedown(function(event){
		$(this).parents("tr").eq(0).css("background-color", "rgb(186, 226, 76)");
		return true;
	});
	$(".ctrl-table-extenible-row",context).click(function(event){
		var link = $(this);
		var tr = $(this).parents("tr:eq(0)");
		
		if(!link.hasClass("ctrl-table-extenible-row-expanded")){
			$.post( link.attr('href'), {}, function(response){
				var n = $("<div></div>").append(response);
				n.find('tr:not(.free)').addClass("tmp-rows");
				
				var after = n.children('tr:not(.free)');
				tr.after( after );
				CtrlAjax.parse(after);
				
			}, "text");
			link.addClass("ctrl-table-extenible-row-expanded");
		}else{
			tr.nextUntil( ":not(tr[class~='tmp-rows'])" ).remove();
			link.removeClass("ctrl-table-extenible-row-expanded");
		}
		return false;
	});
	
	
	
	$(".ctrl-table-num",context).mouseup(function(event){
		$(this).parents("tr").eq(0).css("background-color", "");
		return true;
	});
	
	var timeout;
	
	$(".ctrl-table-quick-search input[type='text']",context).keypress(function (e) {
		if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
			$(this).parent().next().find("input").click();
			return false;
		} else {
			return true;
		}
    });
	
	$(".ctrl-table-quick-search input[type='button']",context).click(function(event){
		var input = $(this).parent().prev().find("input");
		var val = input.val()?input.val():"_";
		//( title, column, value, label, type, process )
		context[0].ctrlArrowTableApplyFilter( "Szukana fraza", "ctrlTableSearchConditions", val, val, "text", false );
		
		return;
		
		CtrlAjax.changeStateVars(input, {search: val},{}, function(context){
			$(".ctrl-table-quick-search input",context).focus();
			
		});
		
	});
	
	function updateField(callback){
		var field = $(context).next("input.ctrl-table-hidden-field");
		if(field.length == 1){
			var ids = field.val().split(";");
		
			$(".ctrl-table-check", context).each(function(){
				
				var checked = $(this).is(":checked");
				var exists = false;
				for( var i = 0; i < ids.length; i++){
					if( ids[i] == $(this).val() ){
						exists = true;
						if(!checked)
							delete ids[i];
					}
				}
				if( checked && !exists )
					ids.push($(this).val());
				
			});
			var newVal = ids.join(";").replace(";;", ";").replace(/^;/, "").replace(/;$/, "");
			field.val(newVal);
			
			//CtrlAjax.changeStateVars(context,{selected: newVal}, false, callback);
		}
	}

	$(".ctrl-table-check-all",context).change(function(event){
		event.stopImmediatePropagation();
		var checked = $(this).attr("checked");
		if(checked)
			$(this).parents("table").find(".ctrl-table-check").attr("checked", "checked");
		else
			$(this).parents("table").find(".ctrl-table-check").removeAttr("checked");
		
		updateField(function(context){
			if(checked)
				$(".ctrl-table-check-all",context).attr("checked", "checked"); 
		});
		return true;
	});
	$(".ctrl-table-check",context).click(function(event){
		updateField();
		event.stopImmediatePropagation();
		return true;
	});
	
	$(".ctrl-table tbody tr td",context).click(function(event){
		
		var check = $(this).parent().find(":checkbox").eq(0);
		if(check.is(":checked"))
			check.removeAttr("checked");
		else
			check.attr("checked","checked");
		return false;
		
	});
	
/*	$(".ctrl-table-list-actions a",context).mousedown(function(){
		var table = $(this).parents("table").eq(0);
		var ids = new Array();
		$("tbody :checked", table).each(function(index,el){ ids.push( $(el).val() )  });
		$(this).attr("href", $(this).attr("href").replace("#key#", ids.join(";")));
		if( ids.length == 0 )
			return false;
	});*/
	
	$(".ctrl-table-list-actions .ctrl-selectable",context).mousedown(function(event){
		if(!$(this).is(".ctrl-action-type-execute")){
			var href = $(this).data( 'link');
			
			if(  href == undefined){
				href = $(this).attr('href');
				$(this).data( 'link', href );
			}
		
			var table = $(this).parents("table");
			var ids = new Array();
			$("tbody :checked", table).each(function(index,el){ if($(this).is(".ctrl-table-check")) ids.push( $(el).val() )  });
			if(ids.length == 0 &&  !$(this).hasClass("ctrl-force-run")){
				alert('Wybierz elementy');
				return false;
			}
			
			var link = href.replace("#key#", ids.join(";"));
			$(this).attr("href", link);
			return true;
		}
		return true;
	});
	
	$(".ctrl-table-list-actions .ctrl-action-type-execute",context).attr("onclick", "");
	$(".ctrl-table-list-actions .ctrl-action-type-execute",context).click(function(event){
		
		var table = $(this).parents("table");
		var ids = new Array();
		$("tbody :checked", table).each(function(index,el){ ids.push( $(el).val() )  });
		
		
		var code = $(this).attr("rel").replace("#key#", ids.join(";"));
		if( ids.length == 0 && !$(this).hasClass("ctrl-force-run") )
				return false;
		
		eval(code);
		
		return false;
	});
	
	if( context[0] ) {
		context[0].ctrlArrowTableApplyFilter = function( title, column, value, label, type, process ) {
				var registry = CtrlAjax.getStateVar(context, 'filtersRegistry');
				
				if(registry != undefined)
					registry = registry.replace(new RegExp('%3D', 'g'), '=');
					
				if(registry != undefined && registry != "W10=" && registry != "W10"){
					
					var count = registry.length % 4;
					if(count > 0)
						count = 4 - count;
					for(var i = 0; i < count; i++)
						registry += '=';
					try{
						var code = "registry = (" + decode64(registry) + ");";
						registry = eval(code);
					}catch(e){
						alert(e);
						registry = { };
					}
				}else{
					registry = { };
				}
				
				
				var tmp = {};
				tmp.value = value;
				tmp.title = title;
				tmp.label = label;
				tmp.strict = false;
				if(process != undefined)
					tmp.process = process;
				else
					tmp.process = true;
				
				registry[column] = tmp;
				registry  = encode64(JSON.stringify(registry));
				
				if(saveFilterCheckbox.attr('checked'))
					$.cookie(data['globalId'], registry, { expires: 30 });
				else
					$.cookie(data['globalId'], null);
				
				CtrlAjax.changeStateVars(context, {'filtersRegistry': registry, 'page': 0}, { }, function(){ 	} );
			};
	}
}